<template>
<div class="box">
    <div class="register">
        <h1>注册</h1>
        <div class="register-form">
            <el-form class="register-form-box" ref="formRef"
            :model="formData"
            :rules="formRules"
            >
                <el-form-item 
                label="用户名:"
                :prop="'username'"
                >
                    <el-input
                    :prefix-icon="User"
                    v-model="formData.username"
                    placeholder="请输入用户名"
                    style="width: 150px;"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item 
                label=" 密码:"
                :prop="'password'"
                >
                    <el-input
                    :prefix-icon="Lock"
                    v-model="formData.password"
                    placeholder="请输入密码"
                    type="password"
                    show-password
                    
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="手机号:"
                :prop="'phone'"
                >
                    <el-input
                    :prefix-icon="Phone"
                    style="width: 150px;"
                    v-model="formData.phone"
                    placeholder="请输入手机号"
                    
                    >
                    </el-input >
                    <el-button type="primary" style="width: 100px;"
                    @click="getCode"
                    :disabled="disabled"
                    >获取验证码</el-button>
                </el-form-item>
                <el-form-item 
                label="验证码:"
                :prop="'code'"
                >
                    <el-input
                    style="width: 150px;"
                    v-model="formData.code"
                    placeholder="请输入验证码"
                    
                    >
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="sumbitRegister" :loading="loading">注册</el-button>
                    <el-button type="info" @click="toLogin">已有账号</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <Teleport to="body">
        <div class="modal-overlay" v-show="isShow">
            <div class="modal-content">
                <div class="verify">
                    验证码为：{{ code }}
                </div>
                <div class="close">
                    <el-button @click="close">关闭</el-button>
                </div>
            </div>
        </div>
    </Teleport>
</div>
</template>
<script setup lang="ts"> 
import { ref, Teleport,reactive, watch, onMounted } from 'vue'
// 导入消息提示
import {ElMessage} from 'element-plus'
// 导入Element Plus的图标组件
import { User, Lock, Phone } from '@element-plus/icons-vue'
// 导入路由
import { useRouter } from 'vue-router'
// 导入接口
import { AuthApi, type RegisterDTO } from '@/api/auth'

// 初始化加载状态
const loading = ref(false)

// 表单 Ref
const formRef = ref() 
// 定义表单数据
const formData=ref({
    username: '',  // 改为空字符串
    password: '',  // 改为空字符串
    phone: '',     // 改为空字符串
    code: '',      // 改为空字符串
})

// 表单验证规则
const formRules = reactive({
    // required:true 表示必填 trigger:'blur' 表示失去焦点时触发
    username:[{required:true,message:'请输入用户名',trigger:'blur'}],
    password:[{required:true,message:'请输入密码',trigger:'blur'}],
    phone:[
        {required:true,message:'请输入手机号',trigger:'blur'},
        { 
            pattern: /^1[3-9]\d{9}$/, // 正则表达式
            message: '请输入正确的手机号格式', 
            trigger: 'blur' 
        } 
    ],
    code:[
        {required:true,message:'请输入验证码',trigger:'blur'},
        { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' }

    ],

})
// 获取路由实例
const router = useRouter()
// 弹窗状态
const isShow = ref(false)
// 关闭弹窗
const close =() =>{
    isShow.value = false
}
// 定义验证码
const code = ref(0)
const disabled = ref(true)
//监听手机号长度,只有长度达到11位才允许获取验证码
watch(()=>formData.value.phone,(newPhone)=>{
    if(newPhone!.length === 11){
        disabled.value = false
    }else{
        disabled.value = true
    }
})  
// 获取验证码
const getCode =()=>{
    // 先判断是否为空,再检查长度
    if(!formData.value.phone || formData.value.phone!.length!==11){
        ElMessage({
            message:'请输入正确的手机号',
            type:'warning'
        })
        return
    }
    //正确之后提示并打开弹窗
    ElMessage({
        message:'验证码已发送',
        type:'success'
    })
    //打开弹窗
    isShow.value = true
    code.value = Math.floor(Math.random()*1000000)
}
//跳转登录页
const toLogin =()=>{
    router.push('/login')
}
// 表单提交
const sumbitRegister = async()=>{
    // 表单验证
    const valid = await formRef.value.validate().catch(() => false)
    if(!valid){
        ElMessage.error("请检查输入的信息")
        return
    }
    // 设置加载状态 避免重复提交
    loading.value = true
    // 发送请求
    try{
        // 获取表单数据排除验证码
        const { username, password, phone } = formData.value
        const submitData: RegisterDTO = {
            userName: username!,
            password: password!,
            phone: phone!
        }
        // 发送注册请求
        await AuthApi.register(submitData)

        // 如果没有错误，则提示注册成功
        ElMessage.success("注册成功")
        setTimeout(()=>{ 
            router.push('/login')
        },2000)
        
    }catch(error){ 
        // ElMessage.error("注册失败")
        // 注册失败后，清除表单数据
        formRef.value.resetFields()
    }finally{
        console.log("11");
        
        // 注册完成后，无论成功失败，都要关闭加载状态
        loading.value = false
        console.log('Loading状态已关闭:', loading.value)
        
    }
    
    // // element-ui表单验证 validate用于验证表单
    // formRef.value.validate((valid: boolean) => { 
    //     // 判断表单是否通过验证
    //     if(!valid){
    //         ElMessage({
    //             message:'请检查输入信息',
    //             type:'error'
    //         })
    //         //不通过禁止提交
    //         return
    //     }
    //     // 通过之后，判断验证码是否正确
    //     if(code.value.toString() === formData.value.code){
    //         ElMessage({
    //             message:'注册成功',
    //             type:'success'
    //         })
    //         // 注册成功把数据保存到localStorage中,
    //         localStorage.setItem('user',JSON.stringify(formData.value))
    //         // 跳转到登录页面
    //         setTimeout(()=>{
    //             router.push('/login')
    //         },3000)
            
    //     }else{
    //         ElMessage({
    //             message:'验证码错误',
    //             type:'error'
    //         })
    //     } 
        
    // })
}


</script>
<style scoped>
.box{
    width: 100%;
    height: 100vh;
    background-image: url('../../assets/auth/authbg.jpg');
    background-size: cover;
    background-repeat: no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
}
.register{
    width: 500px;
    height: 400px;
    background-color: rgba(255,255,255,0.7);
    text-align: center;
    border-radius: 30px;
}
.register-form{
    margin: 0 auto;
    width: 70%;
    height: 70%;
    display: flex;
    text-align: right;
    /* font-size: 20px; */
    /* background-color: aqua; */
}
.register-form-box{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    text-align: center;
    min-width: 300px;
}

.verify {
    margin-bottom: 20px;
    font-size: 16px;
    color: #333;
}

.close {
    margin-top: 10px;
}
</style>